package com.bruip.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理程序
 *
 * @author 王若龙
 * @date 2022-10-05 16:32
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public BaseResponse<String> exceptionHandler(SQLIntegrityConstraintViolationException exception) {
        String message = exception.getMessage();
        log.info("出现异常：{}", message);

        if (message.contains("Duplicate entry")) {
            String[] strings = message.split(" ");
            return BaseResponse.error(strings[2] + " 已存在");
        }
        return BaseResponse.error("未知错误");
    }

    @ExceptionHandler(CustomException.class)
    public BaseResponse<String> exceptionHandler(CustomException exception) {
        String message = exception.getMessage();
        log.info("出现异常：{}", message);
        return BaseResponse.error(message);
    }

}
